package com.ellricky.baselib.ui;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.ellricky.baselib.R;
import com.github.chrisbanes.photoview.PhotoView;


/**
 * Created by april on 2016/11/10.
 */

public class ImageFragment extends Fragment {

    private PhotoView imageView;

    private String url;
    private boolean zoom;

    public static final String IMAGE_URL = "IMAGE_URL";
    public static final String IMAGE_ZOOM = "IMAGE_ZOOM";

    public static ImageFragment getInstance(String url, boolean zoom) {
        ImageFragment imageFragment = new ImageFragment();
        Bundle bundle = new Bundle();
        bundle.putString(ImageFragment.IMAGE_URL, url);
        bundle.putBoolean(ImageFragment.IMAGE_ZOOM, zoom);
        imageFragment.setArguments(bundle);
        return imageFragment;
    }

    public static ImageFragment getInstance(String url) {
        return getInstance(url, true);
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            url = bundle.getString(IMAGE_URL);
            zoom = bundle.getBoolean(IMAGE_ZOOM, true);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.base_image_fragment, container, false);
        imageView = view.findViewById(R.id.photoview);
        imageView.setZoomable(zoom);
        into(url, imageView);

        return view;
    }


    private void into(String url, ImageView iv) {
        if (TextUtils.isEmpty(url)) return;
        Glide.with(this)
                .load(url)
                .apply(new RequestOptions()
                        .placeholder(R.drawable.base_bg_image_placeholder)//加载过程中图片未显示时显示的本地图片
                        .error(R.drawable.base_bg_image_placeholder) //加载异常时显示的图片
                        // .centerCrop()//图片图填充ImageView设置的大小
                        .skipMemoryCache(true)
                        .fitCenter()//缩放图像测量出来等于或小于ImageView的边界范围,该图像将会完全显示
                        .diskCacheStrategy(DiskCacheStrategy.NONE))
                .into(iv);
    }
}
